#!/bin/bash
if [ -e install.lock ]; then
    echo "========已安装======="
    exit
fi

# 查找 composer 的位置并设置为变量
COMPOSER=$(which composer)
if [ -z "$COMPOSER" ]; then
    echo "未找到 composer，请确保已安装 composer"
    exit 1
fi

if [ -f "vendor/autoload.php" ]; then
    echo "依赖已安装，跳过 composer install 步骤"
else
    # 使用 swoole-cli 执行 composer install 安装依赖
    ./swoole-cli $COMPOSER install --no-dev -vvv
fi

# 提示是否执行数据库迁移
echo "即将执行数据库迁移操作 (./swoole-cli bin/hyperf.php migrate)"
read -p "是否确认执行？(yes/no，默认为no): " migrate_confirm
if [[ "$migrate_confirm" != "yes" ]]; then
    echo "已取消数据库迁移操作"
else
    ./swoole-cli bin/hyperf.php migrate
fi

# 提示是否执行数据填充
echo "即将执行数据填充操作 (./swoole-cli bin/hyperf.php db:seed)"
read -p "是否确认执行？(yes/no，默认为no): " seed_confirm
if [[ "$seed_confirm" != "yes" ]]; then
    echo "已取消数据填充操作"
else
    ./swoole-cli bin/hyperf.php db:seed
fi

# 定义递归处理插件安装的函数
# $1: plugin_dir, $2: depth
install_plugin() {
    local plugin_dir=$1
    local depth=${2:-0}  # 默认为第0层
    
    # 限制递归最大层数为3层
    if [ $depth -gt 3 ]; then
        echo "达到最大递归层数限制(3层)，跳过目录: $plugin_dir"
        return
    fi
    
    # 检查是否为需要排除的插件目录
    if [[ "$plugin_dir" == *"mine-admin"* ]] || [[ "$plugin_dir" == *"NEKGod"* ]]; then
        echo "跳过系统关键插件目录: $plugin_dir"
        return
    fi
    
    # 检查是否存在mine.json文件，如果存在则安装该插件
    if [ -f "${plugin_dir}mine.json" ]; then
        # 检查插件是否已安装
        if [ ! -f "${plugin_dir}install.lock" ]; then
            # 提取name字段，使用更精确的方法避免提取错误
            name=$(grep -o '"name"[[:space:]]*:[[:space:]]*"[^"]*"' "${plugin_dir}mine.json" | head -1 | sed 's/"name"[[:space:]]*:[[:space:]]*"\([^"]*\)"/\1/')
            if [ -n "$name" ]; then
                echo "安装插件: $name"
                ./swoole-cli bin/hyperf.php mine-extension:install "$name"
                # 创建install.lock文件表示已安装
                touch "${plugin_dir}install.lock"
            else
                echo "无法从 ${plugin_dir}mine.json 中提取插件名称"
            fi
        else
            echo "插件 $(basename "$plugin_dir") 已安装，跳过"
        fi
    else
        # 如果当前目录没有mine.json，则遍历子目录查找插件
        echo "目录 ${plugin_dir} 不是插件根目录，检查子目录..."
        for sub_dir in "${plugin_dir}"/*/; do
            if [ -d "$sub_dir" ]; then
                install_plugin "$sub_dir" $((depth + 1))
            fi
        done
    fi
}

# 遍历plugin目录下的每个插件目录
for dir in plugin/*/; do
    if [ -d "$dir" ]; then
        # 检查是否为需要排除的顶级插件目录
        if [[ "$(basename "$dir")" != "mine-admin" ]] && [[ "$(basename "$dir")" != "NEKGod" ]]; then
            install_plugin "$dir"
        else
            echo "跳过系统关键插件目录: $dir"
        fi
    fi
done

rm -rf runtime/container
echo 1 > install.lock